#include <stdio.h>
#ifdef sgi
#include <malloc.h>
#endif
#include "neuron.h"

/* DYN_ALLOC.C
 * Functions:
 *
 *	dyn_alloc()	= malloc() with test and error message report
 *	dyn_free()	= free array
 *
 *	dyn_palloc()	= nested malloc() for pointer to array of arrays
 *	dyn_pfree()	= free nested parray
 *
 *	dyn_clr()	= zero elements of an array
 *	dyn_pclr()	= zero elements of a parray
 *
 */

/* DYN_ALLOC
 *	get variable space with error mesg
 */
char *
dyn_alloc(n, sz, msg)
	int n, sz;
	char *msg;
{
	char *p;


/*
fprintf(stderr, "n = %d, sz = %d, msg = %s\n", n, sz, msg);
*/
	p = (char *) malloc(n * sz);
	if (p == NULL) {
		fprintf(stderr, "dyn_alloc(): Unable to malloc %s[%d]\n", msg, n);
		exit(2);
	}
	return(p);
}

void
dyn_free(p)
	char *p;
{
	if (p) {
		free(p);
	}
}

/* DYN_PARRAY
 * allocate a 2-D array as an array of pointers to 1-D vectors
 */
char *
dyn_palloc(n1, sz1, n2, sz2, msg)
	int n1, n2, sz1, sz2;
	char *msg;
{
	register int i;
	register char **p;
	char buf[100];

/*
fprintf(stderr, "n1 = %d, sz1 = %d, n2 = %d, sz2 = %d, msg = %s\n", n1, sz1, n2, sz2, msg);/*
*/

	p = (char **) dyn_alloc(n1 + 1, sz1, msg);	/* extra one to hold null */
	for (i = 0; i < n1; i++) {
		sprintf(buf, "dyn_parray(): %s[%d]", msg, i);
		p[i] = dyn_alloc(n2, sz2, buf);
	}
	p[i] = NULL;	/* last holds null for dyn_pfree() */

/*
fprintf(stderr, "before return: p = %X\n", p);
*/
	return((char *)p);
}

void
dyn_pfree(p)
	register char **p;
{
	register int i;

	if (p == NULL) return;

	for (i = 0; p[i] != NULL; i++) {
		free(p[i]);
	}
	free(p);
}

/* DYN_CLR
 * 	clear elements of pointer array
 */
void
dyn_clr(z, n1, sz1)
	register char **z;
	int n1;
{
	register int i;
	register char * p;

	n1 *= sz1;	/* convert to bytes */
	p = (char *) ((int)z + (i * sz1));
	for (i = 0; i < n1; i++) p[i] = 0;
}


/* DYN_PCLR
 * 	clear elements of pointer array
 */
void
dyn_pclr(z, n1, sz1, n2, sz2)
	register char **z;
	int n1, n2;
{
	register int i, j;
	register char * p;

	n2 *= sz2;	/* convert to bytes */
	for (i = 0; i < n1; i++) {
		p = (char *) ((int)z + (i * sz1));
		for (j = 0; j < n2; j++) p[j] = 0;
	}
}
